package io.renren.modules.handler;

/**
 * @author: xiaomi
 * @date: 2021/5/31
 * @description:
 */

import io.renren.common.component.WsSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.time.LocalDateTime;
import java.util.Hashtable;
import java.util.Map;

/**
 * ws消息处理类
 */
@Component
@Slf4j
public class WsHandler extends AbstractWebSocketHandler {

    /**
     * 在线客户端列表
     * 1、当客户端连接成功后，我们将它的唯一标识以及它的WebSocketSession放入进来
     * 2、有了WebSocketSession，则可以给任何客户端发送消息
     * 复习一下：
     * 1）static final 如果修饰的基本类型，那么基本类型的值不能再修改
     * 2）static final 如果修饰的 Set、List、Map、Array 等，那么是它指向的地址不能再修改，里面的值是可以修改的
     */
    //private static final Map<String, WebSocketSession> CLIENT_MAP = new Hashtable<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("建立ws连接");
        //WsSessionManager.add(session.getId(), session);
        Map<String, Object> map = session.getAttributes();
        String userId = (String) map.get("userId");

        WsSessionManager.add(userId, session);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("发送文本消息");
        // 获得客户端传来的消息
        String payload = message.getPayload();
        log.info("server 接收到系统消息 " + payload);
        log.info("server 发送给客户端的消息 " + payload + "，发送时间:" + LocalDateTime.now().toString());
        //session.sendMessage(new TextMessage("server 发送给的消息 " + payload + "，发送时间:" + LocalDateTime.now().toString()));
        session.sendMessage(message);
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        log.info("发送二进制消息");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("异常处理");
        WsSessionManager.removeAndClose(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("关闭ws连接");
        WsSessionManager.removeAndClose(session.getId());
    }
}
